package yuqueHandler

import (
	"fmt"
	"log"
	"os"
	"runtime"
	"strings"
	"sync"

	. "yuqueDownloader/entity"
	"yuqueDownloader/util"
	. "yuqueDownloader/yuqueHandler/handler"

	"github.com/PuerkitoBio/goquery"
	"golang.org/x/net/html"
)

func init() {
}

func HandleHtml(html string, baseDirPath string, toc *TocStruct, wg *sync.WaitGroup) {
	defer func() {
		// err := recover()
		// if err != nil {
		// 	log.Println("HandleHtml ERROR:", err)
		// }
		if wg != nil {
			wg.Done()
		}
	}()

	if wg != nil {
		wg.Add(1)
	}

	document, err := goquery.NewDocumentFromReader(strings.NewReader(html))
	if err != nil {
		log.Printf("HandleHtml ERROR: %v\n", err)
		runtime.Goexit()
	}

	// bodyNode := findNodeByData(document.Selection, "body")

	bodyNode := findNodeByData2(document.Nodes, "body")

	if bodyNode == nil || bodyNode.FirstChild == nil {
		runtime.Goexit()
	}

	// log.Println("bodyNode FirstChild ======> ", bodyNode.FirstChild)

	content := ""
	superHandler := SuperHandler{
		Content: &content,
		Strong:  false,
		Toc:     toc,
	}

	superHandler.DoAllNode(bodyNode.FirstChild)

	// log.Printf("END %s , final Content: %s\n", toc.Title, content)

	go util.WriteFile(content, "md",
		fmt.Sprintf("%s%cmd", baseDirPath, os.PathSeparator),
		fmt.Sprintf("%03d-%s.md", toc.Idx, toc.Url), wg)
}

// 查询指定节点
func findNodeByData2(nodes []*html.Node, data string) *html.Node {
	var targetNode *html.Node

	for _, node := range nodes {
		if node == nil {
			continue
		}
		if strings.Compare(node.Data, data) == 0 {
			targetNode = node
			return targetNode
		}
		// 递归 子
		tempNodes := make([]*html.Node, 1)
		tempNodes[0] = node.FirstChild
		targetNode = findNodeByData2(tempNodes, data)
		if targetNode != nil {
			return targetNode
		}

		// 递归 Next
		tempNodes[0] = node.NextSibling
		targetNode = findNodeByData2(tempNodes, data)
		if targetNode != nil {
			return targetNode
		}
	}

	return targetNode
}

// 递归找到指定标签 Node
func _findNodeByData(selection *goquery.Selection, data string) *html.Node {
	var bodyNode *html.Node

	selection.Each(func(idx int, slc *goquery.Selection) {
		// log.Printf("%d -- %v\n", idx, slc)
		for _, node := range slc.Nodes {
			// Data--标签类型，Attr--标签属性
			// log.Printf("%d -- Data: %v -- Namespace: %v -- Attr: %v\n",
			// 	idx2, node.Data, node.Namespace, node.Attr)
			if strings.Compare(node.Data, data) == 0 {
				// log.Println("find bodyNode")
				bodyNode = node
				return
			}
		}
		bodyNode = _findNodeByData(slc.Children(), data)
	})

	return bodyNode
}
